﻿package cn.lite3.notepaper
{
	import cn.lite3.notepaper.events.NotepaperEvent;
	import cn.lite3.notepaper.view.NotepaperWindow;
	import cn.lite3.notepaper.managers.NotepaperWindowManager;
	import cn.lite3.notepaper.vo.NotepaperVo;
	import flash.desktop.NativeApplication;
	import flash.desktop.SystemTrayIcon;
	import flash.display.Sprite;
	import air.update.ApplicationUpdaterUI;
	import air.update.events.UpdateEvent;
	import cn.lite3.notepaper.managers.FileIOManager;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.text.TextField;
	import flash.utils.Dictionary;
	import flash.utils.setTimeout;
	
	/**
	 * ...
	 * @author lite3
	 */
	public class Notepaper extends Sprite 
	{
		
		// Instantiate the updater
		private var appUpdater:ApplicationUpdaterUI = new ApplicationUpdaterUI();
		
		private var dataSaving:Boolean = false;
		private var trayIcon:TrayIcon;
		public var fileIOManager:FileIOManager
		
		public function Notepaper():void 
		{
			NativeApplication.nativeApplication.autoExit = false;
			NativeApplication.nativeApplication.addEventListener(Event.EXITING, saveFile);
			
			// init trayIcon
			trayIcon = new TrayIcon(NativeApplication.nativeApplication.icon as SystemTrayIcon);
			
			// check config.ini file path 
			checkConfigFilePath();
			
			// readFile
			fileIOManager = new FileIOManager();
			var str:String = fileIOManager.readData();
			initData(str);
			dataChangeHandler(null);
			// checkForUpdate
			checkForUpdate();
			
			NotepaperWindowManager.getInstance().addEventListener(NotepaperEvent.DATA_CHANGE, dataChangeHandler);
			this.stage.nativeWindow.close();
		}
		
		private function dataChangeHandler(e:NotepaperEvent):void 
		{
			if (!dataSaving)
			{
				dataSaving = true;
				setTimeout(saveFile, 3000);
			}
		}
		
		private function initData(data:String):void
		{
			var xml:XML = new XML(data);
			
			var startAtLogin:Boolean = true;
			if ("false" == xml.config.startAtLogin) startAtLogin = false;
			NativeApplication.nativeApplication.startAtLogin = startAtLogin;
			
			var xmlList:XMLList = xmlList = xml.notepapers.notepaper;
			
			if (xmlList.length() > 0)
			{
				for each(var tmp:XML in xmlList)
				{
					var vo:NotepaperVo = new NotepaperVo(null, tmp.@subject, tmp.@content, tmp.@x, tmp.@y);
					NotepaperWindowManager.getInstance().createWindow(vo);
				}
			}else
			{
				NotepaperWindowManager.getInstance().createWindow();
			}
			
			NotepaperWindowManager.getInstance().hideAll();
		}
		
		// 保存文件
		private function saveFile(e:Event = null):void
		{
			dataSaving = false;
			var xml:XML = <notepaper>
				<notepapers></notepapers>
			</notepaper>
			xml.config.startAtLogin = NativeApplication.nativeApplication.startAtLogin;
			var notepaperXML:XML = xml.notepapers[0];
			var dict:Dictionary = NotepaperWindowManager.getInstance().getDict();
			for each(var window:NotepaperWindow in dict)
			{
				notepaperXML.appendChild(window.getVo().toXML());
			}
			
			fileIOManager.wrightData(xml.toXMLString());
		}
		
		private function checkForUpdate():void 
		{
			// Configuration stuff - see update framework docs for more details
			appUpdater.updateURL = "http://www.lite3.cn/air/notepaper/update.xml"; // Server-side XML file describing update
			appUpdater.isCheckForUpdateVisible = false; // We won't ask permission to check for an update
			appUpdater.addEventListener(UpdateEvent.INITIALIZED, onUpdate); // Once initialized, run onUpdate
			//appUpdater.addEventListener(ErrorEvent.ERROR, onError); // If something goes wrong, run onError
			appUpdater.initialize(); // Initialize the update framework
		}
		
		/*private function onError(event:ErrorEvent):void {
			//Alert.show(event.toString());
		}*/
		
		private function onUpdate(event:UpdateEvent):void {
			appUpdater.checkNow(); // Go check for an update now
		}
		
		private function checkConfigFilePath():void
		{
			var newFile:File = new File(File.documentsDirectory.resolvePath("Notepaper/"+FileIOManager.FileName).nativePath);
			var oldFile:File = new File(File.applicationDirectory.resolvePath(FileIOManager.FileName).nativePath);
			if(!newFile.exists && oldFile.exists)
			{
				var fileStream:FileStream = new FileStream();
				fileStream.open(oldFile, FileMode.READ);
				fileStream.position = 0;
				var data:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
				fileStream.close();
				
				fileStream.open(newFile, FileMode.WRITE);
				fileStream.position = 0;
				fileStream.truncate();
				fileStream.writeUTFBytes(data);
				fileStream.close();
			}
			if(oldFile.exists)
			{
				oldFile.deleteFile();
			}
		}
		
	}
	
}